<template>
  <ElButton type="primary" @click="openDialog('add')"> 添加 </ElButton>
  <Table :options="tableField" :data="dataList" />
  <ElDialog v-model="dialogFlag" :title="dialogTitle">
    <Form :option="formOption" @model="register" />
    <template #footer>
      <ElButton type="primary" @click="save">{{ dialogTitle }}</ElButton>
      <ElButton type="danger" @click="dialogFlag = false">取消 </ElButton>
    </template>
  </ElDialog>
</template>
<script setup lang="jsx">
import Table from "../../../components/Table/index.vue";
import Form from "../../../components/Form/index.vue";
import { useForm } from "../../../hooks/useForm";
const { register, FormParams } = useForm();
import { ref } from "vue";
import { ElButton, ElDialog, ElMessage, ElMessageBox } from "element-plus";
import { getuser, adduser, edituser, deluser } from "../../../api/user";
import { reactive } from "vue";
const tableField = [
  {
    field: "index",
    label: "序号",
    width: "80px",
  },
  {
    field: "username",
    label: "用户名",
  },
  {
    field: "custom",
    label: "操作",
    slots: (obj) => {
      return (
        <>
          <ElButton type="primary" onClick={() => openDialog(obj.row)}>
            {" "}
            修改
          </ElButton>
          <ElButton type="danger" onClick={() => delRow(obj.row)}>
            {" "}
            删除
          </ElButton>
        </>
      );
    },
  },
];
const dataList = ref([]);
function getList() {
  getuser().then((e) => {
    console.log(e);
    dataList.value = e.data;
  });
}
getList();
const dialogFlag = ref(false);
const dialogTitle = ref("");
function openDialog(title) {
  if (title === "add") {
    dialogTitle.value = "添加";
    formOption[0].value = "";
    formOption[1].value = "";
  } else {
    dialogTitle.value = "修改";
    formOption[0].value = title.username;
    formOption[1].value = title.password;
    formOption[2].value = title.id;
  }
  dialogFlag.value = true;
}
const formOption = reactive([
  {
    field: "username",
    label: "用户名",
    value: "12345",
    component: "input",
  },
  {
    field: "password",
    label: "密码",
    value: "",
    component: "password",
  },
  {
    field: "id",
    value: null,
    hidden: true,
  },
]);
function save() {
  console.log(FormParams.value, "点击了保存");
  if (dialogTitle.value === "添加") {
    adduser(FormParams.value).then((e) => {
      ElMessage({ type: "success", message: "添加成功" });
    });
  } else {
    edituser(FormParams.value).then((e) => {
      ElMessage({ type: "success", message: "修改成功" });
    });
  }
  getList();
  dialogFlag.value = false;
}
function delRow(obj) {
  ElMessageBox.confirm(
    "是否确定删除？",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }
  )
    .then(() => {
      deluser(obj.id).then(e=>{
        getList();
      })
    })
    .catch(() => {
      ElMessage({
        type: "提示",
        message: "已取消",
      });
    });
}
</script>